<?php

namespace app\admin\controller;

use app\admin\model\Member;
use app\admin\model\MemberLevel;

class MemberController extends BaseController
{
    public function index()
    {
        $level = (new MemberLevel())->select();
       $this->assign('level',$level);
        return $this->fetch();
    }

     public function read()
    {
        $Member = new Member();
        $data = $Member->leftJoin('w_member_level','w_member.level_id = w_member_level.level_id');
               if(isset($_GET['where'])){
                  $data = $data->where(array_filter($_GET['where']));
               }
                 $count = $data->count();
               $data =$data->page(input('get.page'),input('get.limit'));
               $data =   $data  ->order('member_id desc ');
                $data =   $data->select();
        return json(array('code' => 0, 'msg' => "", 'data' => $data, 'count' =>$count));
    }

    public function save(){

    }

    public function upd(){
        $res = [
            'code'=>0,
            'msg'=>'',
            'token'=>'',
        ];
        $member = new Member();

        $update_status = $member->isUpdate($member)->save(input('post.'));

        if ($update_status){
            $res['msg'] = '更新成功';
            return $res;
        }else{
            $res['code'] = 4;
            $res['msg'] = '更新失败';
            return$res;
        }
    }
    public function build_token(){
        $res = [
            'code'=>0,
            'msg'=>'',
            'token'=>'',
        ];
        $salt = config('api_salt');
        $condition = [
            'member_id'=>input('member_id')
        ];
        $member =  new Member();
        $data = $member->where($condition)->find();
        if (empty($data['api_token'])){
            $token =   md5($data['phone'].$salt);
           $update_status =  $member->where(['member_id'=>$data['member_id']])->update(['api_token'=>$token]);
           if ($update_status){

               $res['code'] =0;
               $res['token'] = $token;
               return $res;
           }else{
               $res['code'] =-4;
               $res['msg'] ='获取token失败';
               return $res;
           }

        }else{
            $res['code'] =0;
            $res['token'] = $data['api_token'];
            return $res;
        }


    }

}
